import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/widgets/border_widget.dart';
import '../../function/states/private_conversation_state.dart';
import '../../function/states/team_conversation_state.dart';
import '../../function/states/user_state.dart';
import '../../function/routes/app_route_manager.dart';
import '../../function/widgets/report_dialog.dart';
import '../../function/widgets/toast_widget.dart';

/// 对话聊天页面
class ConversationChatPage extends StatefulWidget {
  final String chatType; // 'private' 或 'team'
  final String chatId; // 私人聊天：对方用户ID，群聊：群组ID
  final String? chatTitle; // 聊天标题（可选）

  const ConversationChatPage({
    super.key,
    required this.chatType,
    required this.chatId,
    this.chatTitle,
  });

  @override
  State<ConversationChatPage> createState() => _ConversationChatPageState();
}

class _ConversationChatPageState extends State<ConversationChatPage> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  bool _isPrivateChat = false;
  String _currentUserId = '';
  String _chatTitle = '';

  @override
  void initState() {
    super.initState();
    _isPrivateChat = widget.chatType == 'private';
    _currentUserId = UserState.getCurrentUserInfo()?.userId ?? '';
    _initializeChatTitle();

    // 进入页面时清除未读消息
    _clearUnreadMessages();

    // 监听消息变化
    if (_isPrivateChat) {
      PrivateConversationState.conversationMessagesBeacon.subscribe((messages) {
        if (mounted) {
          setState(() {});
          _scrollToBottom();
        }
      });
    } else {
      TeamConversationState.teamMessagesBeacon.subscribe((messages) {
        if (mounted) {
          setState(() {});
          _scrollToBottom();
        }
      });
    }
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 初始化聊天标题
  void _initializeChatTitle() {
    if (widget.chatTitle != null) {
      _chatTitle = widget.chatTitle!;
    } else if (_isPrivateChat) {
      final userInfo = PrivateConversationState.getUserInfo(widget.chatId);
      _chatTitle = userInfo?['userName'] ?? 'Unknown User';
    } else {
      final team = TeamConversationState.getTeamById(widget.chatId);
      _chatTitle = team?.groupName ?? 'Unknown Team';
    }
  }

  /// 清除未读消息
  void _clearUnreadMessages() {
    if (_isPrivateChat) {
      // 清除聊天的未读消息
      PrivateConversationState.markAllMessagesAsRead(
        _currentUserId,
        widget.chatId,
      );
    }
  }

  /// 滚动到底部
  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  /// 格式化时间显示
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${dateTime.month}/${dateTime.day}';
    } else if (difference.inHours > 0) {
      return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    } else {
      return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    }
  }

  /// 发送消息
  void _sendMessage() {
    final message = _messageController.text.trim();
    if (message.isEmpty) return;

    if (_isPrivateChat) {
      PrivateConversationState.sendTextMessage(
        senderId: _currentUserId,
        receiverId: widget.chatId,
        content: message,
      );
    } else {
      TeamConversationState.sendTeamMessage(
        groupId: widget.chatId,
        senderId: _currentUserId,
        content: message,
      );
    }

    _messageController.clear();
  }

  /// 显示举报对话框
  void _showReportDialog() {
    ReportDialog.show(
      context,
      title: _isPrivateChat ? 'Report User' : 'Report Group',
      content:
          _isPrivateChat
              ? 'Please select a reason for reporting this user'
              : 'Please select a reason for reporting this group',
      onReportSuccess: _handleReportSuccess,
    );
  }

  /// 处理举报成功
  void _handleReportSuccess() {
    // 显示举报成功提示
    'Report submitted successfully'.showSuccess();

    AppRouteManager.goBack();

    // 删除对话或群聊
    if (_isPrivateChat) {
      // 删除私人对话
      PrivateConversationState.deleteConversation(
        _currentUserId,
        widget.chatId,
      );
      'You won\'t see this conversation again.'.showSuccess();
    } else {
      // 退出群聊
      TeamConversationState.leaveTeam(widget.chatId, _currentUserId);
      'You won\'t see this group again.'.showSuccess();
    }
  }

  /// 获取消息列表
  List<dynamic> _getMessages() {
    if (_isPrivateChat) {
      return PrivateConversationState.getConversationBetweenUsers(
        _currentUserId,
        widget.chatId,
      );
    } else {
      return TeamConversationState.getTeamMessages(widget.chatId);
    }
  }

  /// 获取用户信息
  Map<String, String>? _getUserInfo(String userId) {
    if (_isPrivateChat) {
      return PrivateConversationState.getUserInfo(userId);
    } else {
      return TeamConversationState.getUserInfo(userId);
    }
  }

  @override
  Widget build(BuildContext context) {
    final messages = _getMessages();

    return Scaffold(
      extendBody: true,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 头部
              _buildHeader(context),

              // 消息列表
              Expanded(
                child: ListView.builder(
                  controller: _scrollController,
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 8.h,
                  ),
                  itemCount: messages.length,
                  itemBuilder: (context, index) {
                    final message = messages[index];
                    return _buildMessageBubble(message);
                  },
                ),
              ),

              // 输入框
              _buildInputField(context),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 0.h, bottom: 12.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => AppRouteManager.goBack(),
            child: Icon(Icons.chevron_left, color: Colors.white, size: 26.w),
          ),

          SizedBox(width: 12.w),

          // 聊天标题
          Expanded(
            child: Text(_chatTitle)
                .fontSize(18.sp)
                .textColor(Colors.white)
                .fontWeight(FontWeight.w600)
                .fontFamily(
                  GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
                ),
          ),

          // 举报按钮
          GestureDetector(
            onTap: _showReportDialog,
            child: Image.asset(
              'assets/images/report.png',
              width: 22.w,
              height: 22.w,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息气泡
  Widget _buildMessageBubble(dynamic message) {
    final isCurrentUser = message.senderId == _currentUserId;
    final userInfo = _getUserInfo(message.senderId);
    final userAvatar = userInfo?['userAvatar'] ?? 'assets/images/avatar1.png';

    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      child: Row(
        mainAxisAlignment:
            isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isCurrentUser) ...[
            // 对方头像
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image: AssetImage(userAvatar),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SizedBox(width: 8.w),
          ],

          // 消息气泡
          Flexible(
            child: Container(
              constraints: BoxConstraints(maxWidth: 280.w),
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color:
                    isCurrentUser
                        ? Colors.white.withValues(alpha: 0.20)
                        : const Color(0x33FF8A3C),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Column(
                crossAxisAlignment:
                    isCurrentUser
                        ? CrossAxisAlignment.end
                        : CrossAxisAlignment.start,
                children: [
                  // 消息内容
                  Text(message.content, style: TextStyle(height: 1.5))
                      .fontSize(13.sp)
                      .textColor(Colors.white)
                      .fontWeight(FontWeight.w600)
                      .fontFamily(
                        GoogleFonts.quicksand(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                      ),

                  SizedBox(height: 4.h),

                  // 时间
                  Text(_formatTime(message.sendTime))
                      .fontSize(12.sp)
                      .textColor(Colors.white)
                      .fontWeight(FontWeight.w400)
                      .fontFamily(
                        GoogleFonts.quicksand(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                      ),
                ],
              ),
            ),
          ),

          if (isCurrentUser) SizedBox(width: 16.w),
        ],
      ),
    );
  }

  /// 构建输入框
  Widget _buildInputField(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Container(
        height: 50.h,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [const Color(0xFF872F1A), const Color(0xFF875720)],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Row(
          children: [
            // 文本输入框
            Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                child: TextField(
                  controller: _messageController,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.quicksand(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                  ),
                  decoration: InputDecoration(
                    hintText: 'Enter What You Want To Say',
                    hintStyle: TextStyle(
                      color: Colors.white.withOpacity(0.6),
                      fontSize: 14.sp,
                      fontFamily:
                          GoogleFonts.quicksand(
                            fontWeight: FontWeight.w400,
                          ).fontFamily,
                    ),
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.zero,
                  ),
                  maxLines: null,
                  textInputAction: TextInputAction.send,
                  onSubmitted: (_) => _sendMessage(),
                ),
              ),
            ),

            // 视频通话按钮（仅单聊）
            if (_isPrivateChat)
              GestureDetector(
                onTap: () {
                  AppRouteManager.navigateToVideoCall(widget.chatId);
                },
                child: Container(
                  width: 34.w,
                  height: 34.w,
                  padding: EdgeInsets.all(3.w),
                  margin: EdgeInsets.only(right: 8.w),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFF8A3C),
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: Colors.white.withOpacity(0.2),
                      width: 1.w,
                    ),
                  ),
                  child: Image.asset(
                    'assets/images/video_call.png',
                    width: 20.w,
                    height: 20.w,
                    color: Colors.white,
                  ),
                ),
              ),

            // 发送按钮
            GestureDetector(
              onTap: _sendMessage,
              child: Container(
                width: 34.w,
                height: 34.w,
                padding: EdgeInsets.all(5.w),
                margin: EdgeInsets.only(right: 8.w),
                decoration: BoxDecoration(
                  color: const Color(0xFFFF8A3C),
                  shape: BoxShape.circle,
                ),
                child: Image.asset(
                  'assets/images/message_send.png',
                  width: 20.w,
                  height: 20.w,
                  color: Colors.white,
                ),
              ),
            ),
          ],
        ),
      ).configBorderWidget(
        borderRadius: 12.r,
        borderColor: Colors.white.withValues(alpha: 0.7),
        borderWidth: 1.w,
      ),
    );
  }
}
